package com.xunqi.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunqi.eduservice.entity.EduSubject;
import com.xunqi.eduservice.entity.excel.SubjectData;
import com.xunqi.eduservice.listener.SubjectExcelListener;
import com.xunqi.eduservice.mapper.EduSubjectMapper;
import com.xunqi.eduservice.service.EduSubjectService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

@Service("eduSubjectService")
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    /**
     * 添加课程分类
     * @param file
     */
    @Override
    public void saveSubject(MultipartFile file,EduSubjectService eduSubjectService) {

        try {
            //文件输入流
            InputStream in = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 查询一级二级分类课程信息
     * @return
     */
    @Override
    public List<EduSubject> getAllOneTwoSubject() {

        //1、先查询出所有分类
        List<EduSubject> eduSubjects = this.baseMapper.selectList(null);

        //2、组装成父子的树形结构
        //2、1找到所有的一级分类
        List<EduSubject> eduSubjectList = eduSubjects.stream().filter(e -> e.getParentId().equals("0"))
                .map((menu) -> {
                    menu.setChildren(getChildrens(menu, eduSubjects));
                    return menu;
                }).collect(Collectors.toList());

        return eduSubjectList;
    }

    private List<EduSubject> getChildrens(EduSubject eduSubject, List<EduSubject> eduSubjects) {

        List<EduSubject> children = eduSubjects.stream().filter(edu -> {
            return edu.getParentId().equals(eduSubject.getId());
        }).map(edu -> {
            //1、找到子菜单(递归)
            edu.setChildren(getChildrens(edu, eduSubjects));
            return edu;
        }).collect(Collectors.toList());

        return children;
    }
}